package com.knowledge.review.designPatterns.structuralpattern.compositepattern;

import java.util.ArrayList;
import java.util.List;

// 菜单组件
public abstract class MenuComponent {
    String name;
    Integer level;
    public void add(MenuComponent menuComponent) {
        throw new UnsupportedOperationException("不支持添加操作!");
    }
    public void remove(MenuComponent menuComponent) {
        throw new UnsupportedOperationException("不支持删除操作!");
    }
    public MenuComponent getChild(Integer i) {
        throw new UnsupportedOperationException("不支持获取子菜单操作!");
    }
    public String getName() {
        throw new UnsupportedOperationException("不支持获取名字操作!");
    }
    public void print() {
        throw new UnsupportedOperationException("不支持打印操作!");
    }
}
// 菜单类
class Menu extends MenuComponent {
    private List<MenuComponent> menuComponentList = new ArrayList<>();
    public Menu(String name,int level){
        this.level = level;
        this.name = name;
    }
    @Override
    public void add(MenuComponent menuComponent) {
        menuComponentList.add(menuComponent);
    }
    @Override
    public void remove(MenuComponent menuComponent) {
        menuComponentList.remove(menuComponent);
    }
    @Override
    public MenuComponent getChild(Integer i) {
        return menuComponentList.get(i);
    }
    @Override
    public void print() {
        for (int i = 1; i < level; i++) {
            System.out.print("--");
        }
        System.out.println(name);
        for (MenuComponent menuComponent : menuComponentList) {
            menuComponent.print();
        }
    }
}
// 子菜单类
class MenuItem extends MenuComponent {
    public MenuItem(String name,int level) {
        this.name = name;
        this.level = level;
    }
    @Override
    public void print() {
        for (int i = 1; i < level; i++) {
            System.out.print("--");
        }
        System.out.println(name);
    }
}

class Test{
    // 测试方法
    public static void main(String[] args) {
        //创建一级菜单
        MenuComponent component = new Menu("系统管理",1);

        MenuComponent menu1 = new Menu("用户管理",2);
        menu1.add(new MenuItem("新增用户",3));
        menu1.add(new MenuItem("修改用户",3));
        menu1.add(new MenuItem("删除用户",3));

        MenuComponent menu2 = new Menu("角色管理",2);
        menu2.add(new MenuItem("新增角色",3));
        menu2.add(new MenuItem("修改角色",3));
        menu2.add(new MenuItem("删除角色",3));
        menu2.add(new MenuItem("绑定用户",3));

        //将二级菜单添加到一级菜单中
        component.add(menu1);
        component.add(menu2);

        //打印菜单名称(如果有子菜单一块打印)
        component.print();
    }
}
 
 